<template>
  <div class="settings">
    <div class="settings-header">
      <button class="back-btn" @click="goBack">
        <span class="icon-back">←</span>
      </button>
      <h1 class="title">设置</h1>
      <div class="placeholder"></div>
    </div>

    <div class="settings-content">
      <!-- 头像设置 -->
      <div class="setting-section">
        <h2 class="section-title">个人信息</h2>
        <div class="setting-item">
          <label class="setting-label">头像</label>
          <div class="avatar-upload">
            <img :src="formData.avatar || defaultAvatar" alt="头像" class="avatar-preview" />
            <input 
              type="file" 
              ref="avatarInput" 
              accept="image/*" 
              @change="handleAvatarChange"
              style="display: none"
            />
            <button class="upload-btn" @click="$refs.avatarInput.click()">
              更换头像
            </button>
          </div>
        </div>

        <!-- 昵称设置 -->
        <div class="setting-item">
          <label class="setting-label">昵称</label>
          <input 
            v-model="formData.nickname" 
            type="text" 
            class="setting-input"
            placeholder="请输入昵称"
            maxlength="20"
          />
        </div>

        <!-- 邮箱显示 -->
        <div class="setting-item">
          <label class="setting-label">邮箱</label>
          <div class="setting-value">{{ userInfo.email || '未设置' }}</div>
        </div>
      </div>

      <!-- 账号安全 -->
      <div class="setting-section">
        <h2 class="section-title">账号安全</h2>
        <div class="setting-item clickable" @click="goToChangePassword">
          <span class="setting-label">修改密码</span>
          <span class="icon-arrow">›</span>
        </div>
      </div>

      <!-- 保存按钮 -->
      <div class="save-section">
        <button class="save-btn" @click="handleSave" :disabled="saving">
          {{ saving ? '保存中...' : '保存修改' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getUserInfoById, updateUserInfo, uploadFile } from '@/api/user'
import defaultAvatar from '@/assets/touxiang.png'

const router = useRouter()
const userStore = useUserStore()

const avatarInput = ref(null)
const saving = ref(false)

const userInfo = ref({
  email: '',
  avatar: '',
  nickname: ''
})

const formData = reactive({
  avatar: '',
  nickname: '',
  avatarFile: null
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 跳转到修改密码页面
const goToChangePassword = () => {
  router.push('/user/change-password')
}

// 处理头像选择
const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    return
  }

  // 验证文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    alert('图片大小不能超过2MB')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.avatar = e.target.result
  }
  reader.readAsDataURL(file)
  
  formData.avatarFile = file
}

// 保存修改
const handleSave = async () => {
  if (!formData.nickname.trim()) {
    alert('昵称不能为空')
    return
  }

  saving.value = true
  try {
    let avatarUrl = userInfo.value.avatar

    // 如果有新上传的头像文件，先上传
    if (formData.avatarFile) {
      console.log('开始上传头像...')
      const uploadRes = await uploadFile(formData.avatarFile)
      console.log('上传响应:', uploadRes)
      
      if (uploadRes.code === 200) {
        // URL可能在msg字段或data字段中
        avatarUrl = uploadRes.msg || uploadRes.data?.url || uploadRes.data
        console.log('获取到的头像URL:', avatarUrl)
        
        if (!avatarUrl) {
          alert('头像上传失败：未获取到图片地址')
          saving.value = false
          return
        }
      } else {
        alert('头像上传失败：' + (uploadRes.msg || '未知错误'))
        saving.value = false
        return
      }
    }

    // 更新用户信息
    const updateData = {
      id: userStore.uid,
      nickName: formData.nickname,
      avatar: avatarUrl
    }

    console.log('准备更新用户信息:', updateData)
    const res = await updateUserInfo(updateData)
    console.log('更新用户信息响应:', res)
    
    if (res.code === 200) {
      alert('保存成功')
      // 更新本地用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        nickName: formData.nickname,
        avatar: avatarUrl
      })
      router.back()
    } else {
      alert(res.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfoById(userStore.uid)
    if (res.code === 200) {
      userInfo.value = {
        email: res.data.email || '',
        avatar: res.data.avatar || '',
        nickname: res.data.nickName || ''
      }
      
      formData.avatar = res.data.avatar || ''
      formData.nickname = res.data.nickName || ''
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.settings {
  min-height: 100vh;
  background: #f5f7fa;
}

.settings-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, #1976d2 0%, #42a5f5 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.2);
}

.back-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 4px 8px;
  display: flex;
  align-items: center;
  transition: transform 0.2s;
}

.back-btn:hover {
  transform: translateX(-4px);
}

.icon-back {
  font-size: 1.8rem;
}

.title {
  font-size: 1.2rem;
  font-weight: 600;
  margin: 0;
}

.placeholder {
  width: 40px;
}

.settings-content {
  padding: 20px;
}

.setting-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 16px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #e5e7eb;
}

.setting-item {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f3f4f6;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-item.clickable {
  cursor: pointer;
  transition: background 0.2s;
}

.setting-item.clickable:hover {
  background: #f9fafb;
  margin: 0 -20px;
  padding-left: 20px;
  padding-right: 20px;
}

.setting-label {
  flex-shrink: 0;
  width: 80px;
  font-weight: 500;
  color: #374151;
}

.setting-value {
  flex: 1;
  color: #6b7280;
}

.setting-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.95rem;
  transition: all 0.2s;
}

.setting-input:focus {
  outline: none;
  border-color: #1976d2;
  box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
}

.avatar-upload {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-preview {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  object-fit: cover;
  border: 2px solid #e5e7eb;
}

.upload-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #1976d2, #1565c0);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.upload-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.3);
}

.upload-btn:active {
  transform: translateY(0);
}

.icon-arrow {
  color: #9ca3af;
  font-size: 1.5rem;
  margin-left: auto;
}

.save-section {
  padding: 20px 0;
}

.save-btn {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #1976d2, #1565c0);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.3);
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(25, 118, 210, 0.4);
}

.save-btn:active:not(:disabled) {
  transform: translateY(0);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .settings-content {
    padding: 16px;
  }

  .setting-section {
    padding: 16px;
  }

  .setting-label {
    width: 70px;
    font-size: 0.9rem;
  }
}
</style>
